package com.lqd.mall.system.service.impl;

import com.lqd.mall.basis.utils.StringUtils;
import com.lqd.mall.interaction.system.SysPostEntity;
import com.lqd.mall.interaction.system.vo.PostVo;
import com.lqd.mall.jpa.service.impl.BaseServiceImpl;
import com.lqd.mall.system.repository.SysPostRepository;
import com.lqd.mall.system.service.ISysPostService;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 零起点
 * @create 2022-03-22 23:20
 */
@Service
public class SysPostServiceImpl
        extends BaseServiceImpl<SysPostRepository, SysPostEntity,Long>
        implements ISysPostService {

    @Resource
    SysPostRepository sysPostRepository;

    @Autowired
    EntityManager entityManager;


    @Override
    @Transactional(readOnly = true)
    public String selectUserPostGroup(Long userId) {

        StringBuilder sql = new StringBuilder();
        sql.append("SELECT  p.post_id as postId ,p.post_name as postName,p.post_code as postCode ");
        sql.append("FROM sys_post p ");
        sql.append("LEFT JOIN sys_user_post up ON up.post_id = p.post_id ");
        sql.append("LEFT JOIN sys_user u ON u.user_id = up.user_id  ");
        sql.append("WHERE u.user_id = :userId ");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.setParameter("userId",userId);
        List<PostVo>  entities = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(PostVo.class)).list();
      //  NativeQueryImplementor implementor = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(PostVo.class));
      //  List<PostVo> list = implementor.list();

        if(CollectionUtils.isEmpty(entities)){
            return StringUtils.EMPTY;
        }
        return entities.stream().map(PostVo::getPostName).collect(Collectors.joining(","));
    }
}
